Symfony EntityType 使用

所有 Entity

use Symfony\Bridge\Doctrine\Form\Type\EntityType;
$builder->add('users', EntityType::class, array(
// 查询的 Entity,显示 username 字段
'class' => 'AppBundle:User',
'choice_label' => 'username',
));

条件查询 Entity, query_builder 返回条件

use Doctrine\ORM\EntityRepository;
use Symfony\Bridge\Doctrine\Form\Type\EntityType;
$builder->add('users', EntityType::class, array(
'class' => 'AppBundle:User',
'query_builder' => function (EntityRepository $er) {
return $er->createQueryBuilder('u')
->orderBy('u.username', 'ASC');
},
'choice_label' => 'username',
));

自定义显示字段,choice_label = function

use Symfony\Bridge\Doctrine\Form\Type\EntityType;
$builder->add('category', EntityType::class, array(
'class' => 'AppBundle:Category',
'choice_label' => function ($category) {
return $category->getDisplayName();
}
));